from db_server import ServerDB
from socket import *
from multiprocessing import Process

HOST = "127.0.0.1"
PORT = 9001
ADDR = (HOST, PORT)
kwargs = {'host': "127.0.0.1",
          'port': 3306,
          'user': "root",
          'password': "123456",
          'db': "dict",
          'charset': "utf8"}


class TcpServer:
    def __init__(self, addr):
        self.addr = addr
        self.sock = self._create()

    def _create(self):
        sock = socket()
        sock.bind(self.addr)
        sock.listen(5)
        return sock


class Server(Process):
    def __init__(self, conn):
        self.conn = conn
        super().__init__(daemon=True)

    def run(self):
        db = ServerDB(kwargs)
        while True:
            msg = self.conn.recv(1024)
            if msg:
                data = msg.decode().split(":")
                if data[0] == "login":
                    password = db.inquire_user(data[1])
                    if password:
                        if password[0][0] == data[2]:
                            self.conn.send(b"1")
                        else:
                            self.conn.send(b"2")
                    else:
                        self.conn.send(b"3")
                elif data[0] == "enroll":
                    results = db.write_user(data[1], data[2])
                    if results:
                        self.conn.send(b"1")
                    else:
                        self.conn.send(b"2")
                elif data[0] == "find":
                    if data[2] != "##":
                        results = db.inquire_word(data[2])
                        print(results)
                        if results:
                            db.write_logs(data[1], data[2])
                            self.conn.send(results[0][0].encode())
                        else:
                            self.conn.send(b"2")
                    else:
                        self.conn.send(b"##")
                elif data[0] == "logs":
                    results = db.inquire_logs(data[1])
                    if results:
                        msg = ''
                        for item in results:
                            msg += ":".join(item[:-1])
                            msg += str(item[-1])+"    \n"
                        self.conn.send(msg.encode())
                    else:
                        self.conn.send(b"2")
            else:
                self.conn.close()
                db.close()
                break


if __name__ == '__main__':
    tcp = TcpServer(ADDR)
    while True:
        conns, addrs = tcp.sock.accept()
        print("Connect from", addrs)
        s = Server(conns)
        s.start()
